/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.binary.view;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import offset.nodes.server.binary.controller.BinaryAttribute;
import offset.nodes.server.controller.AttributeConstants;

/**
 *
 * @author Walter Lütgenau
 */
public class BinaryServlet extends HttpServlet {

    /** Creates a new instance of DownloadServlet */
    public BinaryServlet() {
    }

    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        BinaryAttribute info = (BinaryAttribute) req.getAttribute(BinaryAttribute.ATT_DOWNLOAD);

        if (info == null || info.getInput() == null) {
            res.setStatus(404);
            return;
        }

        String contentType = info.getContentType();
        if (contentType == null || "".equals(contentType)) {
            contentType = "application/octet-stream"; // default
        }
        res.reset();
        res.setContentType(contentType);
        Calendar calendar = Calendar.getInstance();
        if (info.getModification() != null) {
            calendar.setTime(info.getModification());
            res.setDateHeader("Last-Modified", calendar.getTimeInMillis());
        } else {
            calendar.setTime(new Date());
            res.setDateHeader("Last-Modified", calendar.getTimeInMillis());
        }
        
        calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, 1);
        res.setDateHeader("Expires", calendar.getTimeInMillis());
        res.addHeader("Cache-Control", "private,max-age=3600");

        OutputStream out = res.getOutputStream();
        InputStream in = info.getInput();
        byte[] buf = new byte[2048];
        int count = 0;

        while ((count = in.read(buf)) > 0) {
            out.write(buf, 0, count);
        }
        in.close();
    }
}
